package security.utils;

import framework.config.SecurityConfig;
import org.springframework.util.StringUtils;

/**
 * 安全组件Cookie工具
 */
public class SecurityCookieUtil {

    /**
     * 构建Cookie
     *
     * @param name
     * @param value
     * @param securityConfig
     * @param expires
     * @return
     */
    public static StringBuffer buildCookie(SecurityConfig securityConfig, String name, String value, String path, Integer expires) {
        // fix HttpCookie not support SameSite
        StringBuffer buffer = new StringBuffer();
        buffer.append(name).append("=").append(value);
        if (StringUtils.hasText(securityConfig.getCookieDomain())) {
            buffer.append("; Domain").append("=").append(securityConfig.getCookieDomain());
        }
        if (StringUtils.hasText(securityConfig.getCookiePath())) {
            buffer.append("; Path").append("=").append(securityConfig.getCookiePath());
        } else if (StringUtils.hasText(path)) {
            buffer.append("; Path").append("=").append(path);
        }
        if (expires != null && expires > 0) {
            buffer.append("; Max-Age").append("=").append(expires);
        } else if (securityConfig.getCookieMaxAge() != null && securityConfig.getCookieMaxAge() > 0) {
            buffer.append("; Max-Age").append("=").append(securityConfig.getCookieMaxAge());
        }
        if (securityConfig.getCookieSecure() != null && securityConfig.getCookieSecure()) {
            buffer.append("; Secure");
        }
        if (securityConfig.getCookieHttpOnly() != null && securityConfig.getCookieHttpOnly()) {
            buffer.append("; HttpOnly");
        }
        if (StringUtils.hasText(securityConfig.getCookieSameSite())) {
            buffer.append("; SameSite").append("=").append(securityConfig.getCookieSameSite());
        }
        return buffer;
    }

}
